/**@FILE:OssOperator.java
 * @AUTHOR:qingsheng.zheng
 * @DATE:2015-3-31 下午8:44:46*/
package com.fz.tool.aliyun.oss;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSErrorCode;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.ObjectMetadata;

/*******************************************
 * @COMPANY:alibaba
 * @CLASS:OssOperator
 * @DESCRIPTION:
 * @AUTHOR:qingsheng.zheng
 * @VERSION:v1.0
 * @DATE:2015-3-31 下午8:44:46
 *******************************************/
public class OssOperator {
	private OSSClient client;

	public OssOperator(String accessId, String accessKey) {
		this.client = new OSSClient(accessId, accessKey);
	}

	public static OssOperator getInstance(String accessId, String accessKey) {
		OssOperator operator = new OssOperator(accessId, accessKey);
		return operator;
	}

	public void createNewBucket(String bucketName) throws OSSException,
			ClientException {
		try {
			// 创建bucket
			client.createBucket(bucketName);
		} catch (ServiceException e) {
			if (!OSSErrorCode.BUCKES_ALREADY_EXISTS.equals(e.getErrorCode())) {
				// 如果Bucket已经存在，则忽略
				throw e;
			}
		}
	}

	public void uploadImage(String bucketName, String key, InputStream input)
			throws OSSException, ClientException, FileNotFoundException {
		ObjectMetadata objectMeta = new ObjectMetadata();
		// 可以在metadata中标记文件类型
		objectMeta.setContentType("image/jpeg");
		client.putObject(bucketName, key, input, objectMeta);
	}

}
